/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.meego.common.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author TueHM
 */
public class HttpUtils {

    public static String getIp(HttpServletRequest req) {
        String ipAddress = req.getHeader("x-forwarded-for");
        if (ipAddress == null) {
            ipAddress = req.getHeader("X_FORWARDED_FOR");
            if (ipAddress == null) {
                ipAddress = req.getRemoteAddr();
            }
        }
        return ipAddress;
    }

    public static String getCookie(HttpServletRequest req, String cookieName) {
        Cookie[] cookies = req.getCookies();

        for (Cookie item : cookies) {
            if (item.getName().equals(cookieName)) {
                return item.getValue();
            }
        }
        return "";
    }

    public static void setCookie(HttpServletResponse res, String name, String value, String path, int age) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath(path);
        if (age > 0) {
            cookie.setMaxAge(age);
        }
        res.addCookie(cookie);
    }
}
